package async;

import java.util.concurrent.CompletableFuture;
import com.ea.async.Async;

// java -jar ../lib/ea-async.jar async
// java async.AsyncDeepTest
// java -javaagent:../lib/ea-async.jar async.AsyncDeepTest

// 1605 ms, r = 3315906880
public class AsyncDeepTest {
	private static final int N = 1000_0000;
	private static final AsyncFuture<Integer> af = new AsyncFuture<>();
	private static int s_i;

	private static CompletableFuture<Integer> f(long v, int a) {
		if (v == 0) {
			s_i = a;
			Async.await(af.yield());
		} else
			Async.await(f(v >> 8, a + (int)(v & 0xff)));
		return af;
	}

	@SuppressWarnings("UnusedReturnValue")
	private static CompletableFuture<Integer> f() {
		for (int i = 0; i < N; i++)
			Async.await(f(0x100_0000_0000_0000L + i, 0));
		return af;
	}

	public static void main(String[] args) {
		Async.init();
		long t = System.nanoTime();
		long r = 0;
		final Integer DUMMY = 0;
		f();
		for (int i = 0; ; ) {
			r += s_i;
			if (++i >= N)
				break;
			af.complete(DUMMY);
		}
		System.out.println((System.nanoTime() - t) / 1_000_000 + " ms, r = " + r);
	}
}
